<template>
	<view>
		<view v-if="question">
			<view class="info">
				<text id="num">{{(questionIdx + 1) + '.'}}</text>
				<u-tag :text="getTypeTag(question.type)" plain> </u-tag>
				<u-tag style="margin-left: 12rpx;" :text="question.score + '分'" plain type="warning"> </u-tag>
				<u-count-down id="count-down" :time="leftTime" format="HH:mm:ss" @change="onTimeChange">
					<view id="time">
						<view id="time-slot">
							<text
								:id="timeItemStyle">{{ timeData.hours>=10?timeData.hours:'0'+timeData.hours }}</text>
						</view>
						<text id="time-doc">:</text>
						<view id="time-slot">
							<text
								:id="timeItemStyle">{{ timeData.minutes>=10?timeData.minutes:'0'+timeData.minutes }}</text>
						</view>
						<text id="time-doc">:</text>
						<view id="time-slot">
							<text
								:id="timeItemStyle">{{ timeData.seconds>=10?timeData.seconds:'0'+timeData.seconds }}</text>
						</view>
					</view>
				</u-count-down>
			</view>
			<view v-if="question.type == 0">
				<single-choice :change="change" :question="question" :answer="answers[question.questionId.toString()]">
				</single-choice>
			</view>
			<view v-if="question.type == 1">
				<multiple-choice :change="change" :question="question"
					:answer="answers[question.questionId.toString()]">
				</multiple-choice>
			</view>
			<view v-if="question.type == 2">
				<judgement :change="change" :question="question" :answer="answers[question.questionId.toString()]">
				</judgement>
			</view>
			<view v-if="question.type == 3 && answers[question.questionId.toString()]">
				<completion :change="change" :question="question" :answer="answers[question.questionId.toString()]">
				</completion>
			</view>
			<view v-if="(question.type == 4 || question.type == 8) && answers[question.questionId.toString()]">
				<noun-interpretation :change="change" :question="question"
					:answer="answers[question.questionId.toString()]">
				</noun-interpretation>
			</view>
			<view v-if="(question.type == 5 || question.type == 6) && answers">
				<cloze :change="change" :question="question" :answers="answers"></cloze>
			</view>
			<view v-if="(question.type == 7) && answers">
				<listening :change="change" :question="question" :answers="answers"></listening>
			</view>
		</view>
		<view style="height: 100rpx;">
			<view class="footer">
				<u-button id="btn" text="答题卡" @click="toggleSheet"></u-button>
				<u-button id="btn" :text="questionIdx >= questions.length - 1 ? '提交' : '下一题'"
					@click="questionIdx >= questions.length - 1 ? submit() : saveAndNext()"></u-button>
			</view>
		</view>
		<view>
			<u-popup :show="showSheet" :round="50" mode="bottom" :overlayStyle="{background: 'rgba(31, 31, 57, 0.9)'}"
				@close="toggleSheet">
				<view class="sheet">
					<view id="sheet-title">
						<text>答题卡</text>
					</view>
					<view @click="toggleSheet" id="sheet-close">
						<u-icon size="48" name="close"></u-icon>
					</view>
					<view id="btns">
						<view style="margin: 8rpx;" v-for="(item,index) in questions" :key="index">
							<view @click="sheetSwitchQuestion(index)"
								:id="isAnswered(item.questionId) ? 'btn-answered' : 'btn'">
								<view style="display: flex; flex-direction: column; text-align: center;">
									<text>{{index+1}}</text>
								</view>
							</view>
						</view>
					</view>
					<view id="sheet-info">
						<view style="display: flex; flex-direction: row; justify-content: center;">
							<text style="width: 160rpx;">总计: {{total}}</text>
							<text style="width: 160rpx;">未答: {{total-answered}}</text>
						</view>
					</view>
				</view>
			</u-popup>
			<view>
				<u-modal :show="submitShow" showCancelButton confirmColor="#3d5cff" @cancel="cancelSubmitShow"
					@confirm="confirmSubmitShow" :confirmText="submitDirectly ? '提交' : '继续提交'" :asyncClose="true">
					<text>{{submitDirectly ? '确认提交吗？' : '你还有'+(total-answered)+'题未作答！'}}</text>
				</u-modal>
				<u-modal :show="showEnd" confirmColor="#3d5cff"
					@confirm="confirmEnd" confirmText="确定">
					<u-icon size="72" color="#ff6905" name="warning-fill"></u-icon>
					<view style="display: flex; flex-direction: column; justify-content: center;">
						<text style="font-size: 42rpx;">考试结束！</text>
					</view>
				</u-modal>
			</view>
		</view>
	</view>
</template>

<script>
	import SingleChoice from '../../templates/question/SingleChoice.vue';
	import MultipleChoice from '../../templates/question/MultipleChoice.vue';
	import Judgement from '../../templates/question/Judgement.vue';
	import Completion from '../../templates/question/Completion.vue';
	import NounInterpretation from '../../templates/question/NounInterpretation.vue';
	import Cloze from '../../templates/question/Cloze.vue';
	import Listening from '../../templates/question/Listening.vue';

	const api = require('api.js');
	var _this = null;
	export default {
		data() {
			return {
				choiceNames: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
					'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
				],
				leftTime: 0,
				timeData: {
					hours: 0,
					minutes: 0,
					seconds: 0
				},
				timeItemStyle: 'time-item',
				examId: 0,
				paperId: 0,
				examInfo: {},
				questions: {},
				answers: {},
				questionIdx: -1,
				question: null,
				showSheet: false,
				total: 0,
				answered: 0,
				showEnd: false,
				submitShow: false,
				submitDirectly: false,
				changed: new Set([])
			}
		},
		components: {
			SingleChoice,
			MultipleChoice,
			Judgement,
			Completion,
			NounInterpretation,
			Cloze,
			Listening
		},
		methods: {
			onTimeChange(e) {
				_this.timeData = e;
				if (_this.timeData.days <= 0 && _this.timeData.hours <= 0 && _this.timeData.minutes <= 0 && _this.timeData.seconds <= 60) {
					_this.timeItemStyle = e.seconds % 2 == 0 ? 'time-item-warn' : 'time-item';
					if (_this.timeData.seconds == 1) {
						_this.saveAnswer();
						api.getAsync('/api/paper/submit/' + _this.examInfo.paperId, {}, (res) => {}, (err) => {})
					}
					if (_this.timeData.seconds <= 0) {
						_this.showEnd = true;
					}
				}
			},
			confirmEnd: function() {
				var pages = getCurrentPages();
				if (pages.length > 1) {
					uni.navigateBack({
						url: pages[pages.length - 2].url
					})
				}
			},
			switchQuestion: function(idx) {
				if (idx >= _this.questions.length) {
					return;
				}
				_this.questionIdx = idx;
				_this.question = _this.questions[idx];
				_this.$forceUpdate();
			},
			getTypeTag: function(type) {
				if (type == 0) {
					return '单选';
				} else if (type == 1) {
					return '多选';
				} else if (type == 2) {
					return '判断';
				} else if (type == 3) {
					return '填空';
				} else if (type == 4) {
					return '名词解释';
				} else if (type == 5) {
					return '完形填空';
				} else if (type == 6) {
					return '阅读理解';
				} else if (type == 7) {
					return '听力';
				} else if (type == 8) {
					return '简答';
				}
			},
			toggleSheet: function() {
				_this.showSheet = !_this.showSheet;
			},
			sheetSwitchQuestion: function(idx) {
				_this.saveAnswer();
				_this.toggleSheet();
				_this.switchQuestion(idx);
			},
			isAnswered: function(questionId) {
				for (var i = 0; i < _this.questions.length; i++) {
					if (_this.questions[i].questionId == questionId) {
						var question = _this.questions[i];
						if (question.subQuestions != null && question.subQuestions.length > 0) {
							for (var j = 0; j < question.subQuestions.length; j++) {
								if (!_this.isAnswered(question.subQuestions[j].questionId)) {
									return false;
								}
							}
							return true;
						}
						break;
					}
				}
				return _this.answers[questionId] && _this.answers[questionId].content != undefined && _this.answers[
					questionId].content != null && _this.answers[questionId].content != ''
			},
			calcAnswered: function() {
				var k = 0;
				for (var i = 0; i < _this.questions.length; i++) {
					var question = _this.questions[i];
					if (question.subQuestions != null && question.subQuestions.length > 0) {
						for (var j = 0; j < question.subQuestions.length; j++) {
							if (_this.isAnswered(question.subQuestions[j].questionId)) {
								k++;
							}
						}
					} else {
						if (_this.isAnswered(question.questionId)) {
							k++;
						}
					}
				}
				_this.answered = k;
			},
			updateAnswer: function(id, content) {
				_this.answers[id].content = content;
				_this.$forceUpdate();
			},
			change: function(questionId) {
				_this.changed.add(questionId);
			},
			saveAnswerById: function(questionId) {
				for (var i = 0; i < _this.questions.length; i++) {
					if (_this.questions[i].questionId == questionId) {
						if (_this.question.subQuestions != null && _this.question.subQuestions.length > 0) {
							for (var j = 0; j < _this.question.subQuestions.length; j++) {
								var questionId = _this.question.subQuestions[j].questionId;
								api.postAsync('/api/paper/answer/save', {
									content: _this.answers[questionId].content,
									id: _this.answers[questionId].id
								}, (res) => {}, (err) => {})
							}
							_this.calcAnswered();
							return;
						}
					}
				}
				api.postAsync('/api/paper/answer/save', {
					content: _this.answers[questionId].content,
					id: _this.answers[questionId].id
				}, (res) => {}, (err) => {})
				_this.calcAnswered();
			},
			saveAnswer: function() {
				_this.changed.forEach((ele) => {
					_this.saveAnswerById(ele);
				});
				_this.changed.clear();
			},
			saveAndNext: function() {
				_this.saveAnswer();
				_this.switchQuestion(_this.questionIdx + 1);
			},
			submit: function() {
				_this.saveAnswer();
				_this.submitDirectly = _this.answered >= _this.total;
				_this.submitShow = true;
			},
			cancelSubmitShow: function() {
				_this.submitShow = false;
			},
			confirmSubmitShow: function() {
				api.getSync('/api/paper/submit/' + _this.examInfo.paperId, {}, (res) => {
					var pages = getCurrentPages();
					if (pages.length > 1) {
						uni.navigateBack({
							url: pages[pages.length - 2].url
						})
					}
				}, (err) => {});
				_this.submitShow = false;
			}
		},
		onLoad(options) {
			_this = this;
			_this.back = getCurrentPages().length > 1;
			_this.examId = options.examId;
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			var errorBack = function(msg) {
				uni.hideLoading();
				var pages = getCurrentPages();
				if (pages.length > 1) {
					uni.navigateBack({
						url: pages[pages.length - 2].url
					})
				}
				setTimeout(() => {
					uni.showToast({
						icon: 'error',
						title: msg,
						duration: 2000
					});
				}, 200)
			}
			api.getSync('/api/exam/info/' + _this.examId, {}, (res) => {
				if (res.code == 200) {
					uni.hideLoading();
					_this.examInfo = res.data;
					api.getSync('/api/paper/start/' + _this.examInfo.paperId, {}, (ress) => {
						if (ress.code != 200) {
							if (ress.code == 40402012) {
								api.getSync('/api/user/qrcode/create?type=paper_check_face&option='+ _this.examInfo.paperId + '_' + api.user.userid, {}, (suc) => {
									uni.navigateTo({
										url: '../face/faceconfirm?code=' + suc.data.code
									});
								}, (errr)=>{});
								return;
							}
							errorBack(ress.msg);
						} else {
							var date = new Date(_this.examInfo.endTime).getTime();
							_this.leftTime = date - new Date().getTime();
							api.getSync('/api/paper/detail/' + _this.examInfo.paperId, {}, (res2) => {
								if (res2.code == 200) {
									_this.questions = res2.data.questions;
									var t = 0;
									for (var i = 0; i < _this.questions.length; i++) {
										var question = _this.questions[i];
										if (question.subQuestions != null && question.subQuestions
											.length > 0) {
											t += question.subQuestions.length;
										} else {
											t++;
										}
									}
									_this.total = t;
									_this.switchQuestion(0);
									api.getSync('/api/paper/answers/my/' + _this.examInfo
									.paperId, {}, (res3) => {
										if (res3.code == 200) {
											res3.data.forEach(ele => {
												var answer = {
													id: ele.id,
													questionId: ele.questionId,
													content: ele.content
												};
												_this.answers[ele.questionId] =
													answer;
											});
											_this.calcAnswered();
											_this.$forceUpdate();
										} else {
											errorBack(res3.msg);
										}
									}, (err) => {
										errorBack('网络错误');
									});
								}
							}, (err) => {
								errorBack('网络错误');
							});
						}
					}, (err) => {
						errorBack('网络错误');
					});
				} else {
					errorBack(res.msg);
				}
			}, (err) => {
				errorBack('网络错误');
			});
		}
	}
</script>

<style lang="scss" scoped>
	.info {
		padding-top: calc(var(--status-bar-height) + 24rpx);
		padding-left: 24rpx;
		display: flex;
		flex-direction: row;

		#num {
			font-size: 42rpx;
			margin-right: 12rpx;
		}
		
		#count-down {
			position: absolute;
			right: 24rpx;
			color: white;
			font-weight: 1000;
		
			#time {
				display: flex;
				flex-direction: row;
			}
		
			#time-slot {
				background: #4398ff;
				border-radius: 12rpx;
				padding: 6rpx;
			}
		
			#time-item {
				font-size: 32rpx;
			}
			
			#time-item-warn {
				font-size: 32rpx;
				color: red;
			}
		
			#time-doc {
				padding: 0 8rpx;
				font-size: 32rpx;
				color: #4398ff;
			}
		}
	}

	.footer {
		position: fixed;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		padding-left: 24rpx;
		padding-right: 24rpx;
		bottom: 0;
		background: white;
		box-shadow: 0 -16rpx 24rpx rgba(184, 184, 210, 0.2);

		#btn {
			margin: 10rpx 16rpx 10rpx;
			width: 320rpx;
			height: 100rpx;
			border-width: 0;
			border-radius: 20rpx;
			background-color: $primary-color;
			color: white;
		}
	}

	.sheet {
		height: 900rpx;
		position: relative;

		#sheet-title {
			position: absolute;
			color: rgba(31, 31, 57, 1);
			font-size: 36rpx;
			font-weight: bold;
			width: 100%;
			height: 80rpx;
			text-align: center;
			padding-top: 36rpx;
		}

		#sheet-close {
			position: absolute;
			padding-top: 36rpx;
			padding-left: 674rpx;
			z-index: 99;
		}

		#btns {
			height: 700rpx;
			position: absolute;
			padding-top: 108rpx;
			padding-left: 48rpx;
			padding-right: 48rpx;
			display: flex;
			flex-direction: column;
			flex-flow: wrap;
			align-content: flex-start;

			#btn {
				width: 72rpx;
				height: 72rpx;
				background: white;
				border-radius: 100%;
				display: flex;
				flex-direction: column;
				justify-content: center;
				text-align: center;
				color: $primary-color;
				border: 2rpx solid $primary-color;
			}

			#btn:active {
				background: rgba(0, 0, 0, 0.1);
			}

			#btn-answered {
				width: 72rpx;
				height: 72rpx;
				background: $primary-color;
				border-radius: 100%;
				display: flex;
				flex-direction: column;
				justify-content: center;
				text-align: center;
				color: white;
				border: 2rpx solid $primary-color;
			}
		}

		#sheet-info {
			position: absolute;
			width: 100%;
			color: rgba(31, 31, 57, 1);
			font-size: 28rpx;
			font-weight: bold;
			text-align: center;
			bottom: 40rpx;
		}
	}
</style>
